﻿using DevelopTool.Common;
using DevelopTool.Forms.BaseForms;
using DevelopTool.Model;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;

namespace DevelopTool.Forms.CommonForms
{
    /// <summary>
    /// DataGridView筛选条件下拉窗口
    /// </summary>
    public partial class DataGridViewFilterForm : BaseUIForm
    {
        /// <summary>
        /// 当前选中的节点集合
        /// </summary>
        private HashSet<TreeNode> checkTreeNodes = new HashSet<TreeNode>();

        /// <summary>
        /// 匹配方式
        /// </summary>
        private string matching = "包含";

        /// <summary>
        /// 运算符
        /// </summary>
        private string operatorStr = "或者【OR】";

        /// <summary>
        /// 所属控件/窗体
        /// </summary>
        private Control owner;

        /// <summary>
        /// 实例化DataGridView筛选条件下拉窗口
        /// </summary>
        /// <param name="owner">当前窗口</param>
        /// <param name="dataGridViewColumnCollection">DataGridView列集合</param>
        public DataGridViewFilterForm(Control owner, DataGridViewColumnCollection dataGridViewColumnCollection)
        {
            InitializeComponent();
            this.owner = owner;

            Init(dataGridViewColumnCollection);
        }


        private void DataGridViewFilterForm_Load(object sender, EventArgs e)
        {
            ThemHelper.SetSystemThem(this);
        }

        /// <summary>
        /// 初始化树菜单列表
        /// </summary>
        /// <param name="columnCollection"></param>
        private void Init(DataGridViewColumnCollection dataGridViewColumnCollection)
        {
            //填充树下拉菜单的数据
            foreach (DataGridViewColumn column in dataGridViewColumnCollection)
            {
                if (!column.Visible) continue;

                if (column.ValueType == null) continue;

                TreeNode treeNode = new TreeNode($"{column.HeaderText}【{column.ValueType.Name}】");
                treeNode.Tag = column;
                tvQueryColumns.Nodes.Add(treeNode);

                if (column.Tag is DataGridColumn gridColumn)
                {
                    if (gridColumn.ColumnType.HasFlag(ColumnType.DefaultFilter))// && checkTreeNodes.Count <= 0
                    {
                        treeNode.Checked = true;//选中默认查询的列
                        checkTreeNodes.Add(treeNode);
                    }
                }
            }

            rdogOperator.SelectedIndex = 0;
            rdogMatching.SelectedIndex = 0;
        }


        /// <summary>
        /// 显示窗口
        /// </summary>
        /// <param name="control"></param>
        public void ShowForm(Control control)
        {
            Width = control.Width;
            var controlPoint = owner.PointToScreen(control.Location);

            Location = new Point(controlPoint.X, controlPoint.Y + control.Height);

            Show();

            GenerateFilter();
        }


        /// <summary>
        /// 获取筛选表达式
        /// </summary>
        /// <param name="checkMatching"></param>
        /// <param name="checkColumns"></param>
        /// <returns></returns>
        public string GetFilter(string keywordStr)
        {
            //多参数
            var keywords = keywordStr.Split(new char[] { ';', '；' }, StringSplitOptions.RemoveEmptyEntries);
            //  if (keywords.Length > 1)
            //  {
            GenerateFilter(keywords.ToList());
            //}

            if (string.IsNullOrEmpty(keywordStr) || string.IsNullOrWhiteSpace(textBoxFilter.Text)) return "";

            string filter = textBoxFilter.Text;
            foreach (TreeNode node in checkTreeNodes)
            {
                DataGridViewColumn column = node.Tag as DataGridViewColumn;

                filter = filter.Replace(column.HeaderText, column.DataPropertyName);
            }

            keywordStr = keywordStr.Replace("'", "''");
            keywordStr = keywordStr.Replace("[", "[[]");
            keywordStr = keywordStr.Replace("%", @"[%]");
            keywordStr = keywordStr.Replace("*", @"[*]");
            keywordStr = keywordStr.Replace(";", "");
            keywordStr = keywordStr.Replace("；", "");

            filter = filter.Replace("@值@", keywordStr);

            return filter;
        }


        /// <summary>
        /// 当前窗口失去焦点事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DataGridViewCondition_Deactivate(object sender, System.EventArgs e)
        {

            this.Hide();//隐藏当前窗口
        }

        /// <summary>
        /// 运算符选中事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="index"></param>
        /// <param name="text"></param>
        private void rdogOperator_ValueChanged(object sender, int index, string text)
        {
            if (!string.IsNullOrEmpty(text))
            {
                operatorStr = text;
                GenerateFilter();
            }
        }


        /// <summary>
        /// 匹配方式选择事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="index"></param>
        /// <param name="text"></param>
        private void rdogMatching_ValueChanged(object sender, int index, string text)
        {
            if (!string.IsNullOrEmpty(text))
            {
                matching = text;
                GenerateFilter();
            }
        }


        /// <summary>
        /// 树节点选择事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tvQueryColumns_AfterCheck(object sender, TreeViewEventArgs e)
        {
            checkTreeNodes.Clear();
            foreach (TreeNode node in tvQueryColumns.Nodes)
            {
                if (node.Checked)
                {
                    checkTreeNodes.Add(node);
                }
            }
            GenerateFilter();
        }


        /// <summary>
        /// 生成筛选表达式
        /// </summary>
        private void GenerateFilter(List<string> values = null)
        {
            if (checkTreeNodes == null || checkTreeNodes.Count <= 0)
            {
                textBoxFilter.Text = "";
                return;
            }

            if (values == null || values.Count <= 1)
            {
                values = new List<string>() { "@值@" };
            }

            string oper = "";
            switch (operatorStr)
            {
                case "或者【OR】":
                    oper = " OR ";
                    break;
                case "并且【AND】":
                    oper = " AND ";
                    break;
            }

            string filter = string.Empty;
            foreach (TreeNode node in checkTreeNodes)
            {
                DataGridViewColumn column = node.Tag as DataGridViewColumn;

                List<string> conditions = new List<string>();

                foreach (string value in values)
                {
                    //字符串类型
                    if (column.ValueType == typeof(string))
                    {
                        switch (matching)
                        {
                            case "包含":
                                conditions.Add(column.HeaderText + $" LIKE '*{value}*' ");
                                break;
                            case "不包含":
                                conditions.Add(column.HeaderText + $" NOT LIKE '*{value}*' ");
                                break;
                            case "等于":
                                conditions.Add(column.HeaderText + $" = '{value}' ");
                                break;
                            case "不等于":
                                conditions.Add(column.HeaderText + $" <> '{value}' ");
                                break;
                            case "开头":
                                conditions.Add(column.HeaderText + $" LIKE '{value}*' ");
                                break;
                            case "结尾":
                                conditions.Add(column.HeaderText + $" LIKE '*{value}' ");
                                break;
                        }
                    }
                    //数值类型
                    else if (column.ValueType == typeof(int) || column.ValueType == typeof(decimal) || column.ValueType == typeof(double) || column.ValueType == typeof(float))
                    {
                        switch (matching)
                        {
                            case "不等于":
                                conditions.Add(column.HeaderText + $" <> '{value}' ");
                                break;
                            case "大于":
                                conditions.Add(column.HeaderText + $" > {value} ");
                                break;
                            case "小于":
                                conditions.Add(column.HeaderText + $" < {value} ");
                                break;
                            default:
                                conditions.Add(column.HeaderText + $" = {value} ");
                                break;
                        }
                    }
                    else
                    {
                        conditions.Add(column.HeaderText + $" = {value} ");
                    }

                }

                string conditionStr = string.Empty;
                if (values != null && values.Count > 1)//拼接多个查询条件值
                {
                    conditionStr = "(";
                    foreach (string condition in conditions)
                    {
                        conditionStr += condition + "AND ";
                    }
                    conditionStr = conditionStr.RemoveLastStr("AND ");//删除最后一个AND运算符
                    conditionStr += ")";
                }
                else
                {
                    foreach (string condition in conditions)//拼接一个查询条件值
                    {
                        conditionStr += condition;
                    }
                }
                conditionStr += oper;
                filter += conditionStr;
            }

            if (!string.IsNullOrEmpty(filter))
            {
                filter = filter.RemoveLastStr(oper);//删除最后一个运算符
            }
            textBoxFilter.Text = filter;
        }


    }
}
